﻿using Android.Content;
using Android.Net.Wifi;
using Android.OS;
using AvaloniaDevice.Common.Services;
using System.Runtime.CompilerServices;
using WifiInfo = AvaloniaDevice.Common.WIFI.WifiInfo;

[assembly: Dependency("AndroidWifiService", LoadHint.Default)]
namespace AvaloniaAndroid.Core.WIFI
{
    public class AndroidWifiService : IWifiService
    {
        private readonly WifiManager _wifiManager;
        private WifiReceiver _wifiReceiver;

        public bool IsSupported => true;

        public string PlatformRestrictions =>
            Build.VERSION.SdkInt >= BuildVersionCodes.Q ?
            "Android 10及以上版本需要手动在设置中开关WiFi" :
            "全功能支持";


        public AndroidWifiService()
        {
            _wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
        }

        public bool IsWifiEnabled()
        {
            return _wifiManager.IsWifiEnabled;
        }

        public async Task SetWifiEnabled(bool enabled)
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Q)
            {
                // Android 10及以上需要使用Settings面板
                var intent = new Android.Content.Intent(Android.Provider.Settings.Panel.ActionWifi);
                intent.AddFlags(Android.Content.ActivityFlags.NewTask);
                Android.App.Application.Context.StartActivity(intent);
                await Task.Delay(1000); // 等待用户操作
            }
            else
            {
                // Android 10以下可以直接设置
                _wifiManager.SetWifiEnabled(enabled);
                await Task.Delay(1000);
            }
        }

        public async Task<List<WifiInfo>> GetAvailableNetworks()
        {
            var result = new List<WifiInfo>();

            // 确保WiFi已开启
            if (!IsWifiEnabled())
                return result;

            // 注册广播接收器监听扫描结果
            var tcs = new TaskCompletionSource<List<ScanResult>>();
            _wifiReceiver = new WifiReceiver(_wifiManager, tcs);

            var filter = new IntentFilter(WifiManager.ScanResultsAvailableAction);
            Android.App.Application.Context.RegisterReceiver(_wifiReceiver, filter);

            // 开始扫描
            bool scanStarted = _wifiManager.StartScan();

            if (!scanStarted)
            {
                Android.App.Application.Context.UnregisterReceiver(_wifiReceiver);
                return result;
            }

            // 等待扫描结果
            var scanResults = await tcs.Task;
            Android.App.Application.Context.UnregisterReceiver(_wifiReceiver);

            // 转换结果
            foreach (var scanResult in scanResults.DistinctBy(r => r.Ssid))
            {
                result.Add(new WifiInfo
                {
                    Ssid = scanResult.Ssid.Trim('"'),
                    Bssid = scanResult.Bssid,
                    SignalStrength = CalculateSignalStrength(scanResult.Level),
                    IsEncrypted = !string.IsNullOrEmpty(scanResult.Capabilities),
                    EncryptionType = GetEncryptionType(scanResult),
                    IsConnected = IsNetworkConnected(scanResult.Ssid)
                });
            }

            return result;
        }

        public async Task<bool> ConnectToWifi(string ssid, string password = null)
        {
            try
            {
                // 移除已保存的同名网络
                var configuredNetworks = _wifiManager.ConfiguredNetworks;
                if (configuredNetworks != null)
                {
                    foreach (var network in configuredNetworks.Where(n => n.Ssid.Trim('"') == ssid))
                    {
                        _wifiManager.RemoveNetwork(network.NetworkId);
                    }
                }

                // 创建新的网络配置
                var config = new WifiConfiguration
                {
                    Ssid = $"\"{ssid}\""
                };

                // 根据加密类型设置不同的配置
                if (string.IsNullOrEmpty(password))
                {
                    // 开放网络
                    config.AllowedKeyManagement.Set((int)KeyManagementType.None);
                }
                else
                {
                    // WPA/WPA2加密网络
                    config.PreSharedKey = $"\"{password}\"";
                    config.AllowedKeyManagement.Set((int)KeyManagementType.WpaPsk);
                    //config.AllowedProtocols.Set((int)WifiProtocol.Wpa);
                    //config.AllowedProtocols.Set((int)WifiProtocol.Rsn);
                    config.AllowedAuthAlgorithms.Set((int)AuthAlgorithmType.Open);
                }

                // 添加网络并连接
                int networkId = _wifiManager.AddNetwork(config);
                if (networkId == -1)
                    return false;

                bool enabled = _wifiManager.EnableNetwork(networkId, true);
                bool reconnected = _wifiManager.Reconnect();

                // 等待连接成功
                await Task.Delay(5000);
                return IsNetworkConnected(ssid);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"连接WiFi失败: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> DisconnectFromWifi(string ssid)
        {
            try
            {
                var configuredNetworks = _wifiManager.ConfiguredNetworks;
                if (configuredNetworks != null)
                {
                    foreach (var network in configuredNetworks.Where(n => n.Ssid.Trim('"') == ssid))
                    {
                        _wifiManager.DisableNetwork(network.NetworkId);
                        _wifiManager.SaveConfiguration();
                    }
                }

                _wifiManager.Disconnect();
                await Task.Delay(1000);
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"断开WiFi失败: {ex.Message}");
                return false;
            }
        }

        public WifiInfo GetConnectedWifi()
        {
            var connectionInfo = _wifiManager.ConnectionInfo;
            if (connectionInfo == null || string.IsNullOrEmpty(connectionInfo.SSID))
                return null;

            return new WifiInfo
            {
                Ssid = connectionInfo.SSID.Trim('"'),
                Bssid = connectionInfo.BSSID,
                SignalStrength = CalculateSignalStrength(connectionInfo.Rssi),
                IsConnected = true
            };
        }

        // 计算信号强度百分比
        private int CalculateSignalStrength(int level)
        {
            if (level <= -100)
                return 0;
            if (level >= -50)
                return 100;
            return 2 * (level + 100);
        }

        // 获取加密类型
        private string GetEncryptionType(ScanResult scanResult)
        {
            if (string.IsNullOrEmpty(scanResult.Capabilities))
                return "开放";

            if (scanResult.Capabilities.Contains("WPA3"))
                return "WPA3";
            if (scanResult.Capabilities.Contains("WPA2"))
                return "WPA2";
            if (scanResult.Capabilities.Contains("WPA"))
                return "WPA";
            if (scanResult.Capabilities.Contains("WEP"))
                return "WEP";

            return "未知";
        }

        // 检查网络是否已连接
        private bool IsNetworkConnected(string ssid)
        {
            var connectedWifi = GetConnectedWifi();
            return connectedWifi != null && connectedWifi.Ssid == ssid.Trim('"');
        }
    }

    // WiFi扫描结果接收器
    public class WifiReceiver : BroadcastReceiver
    {
        private readonly WifiManager _wifiManager;
        private readonly TaskCompletionSource<List<ScanResult>> _tcs;

        public WifiReceiver(WifiManager wifiManager, TaskCompletionSource<List<ScanResult>> tcs)
        {
            _wifiManager = wifiManager;
            _tcs = tcs;
        }

        public override void OnReceive(Context context, Intent intent)
        {
            bool success = intent.GetBooleanExtra(WifiManager.ScanResultsAvailableAction, false);
            if (success)
            {
                var results = _wifiManager.ScanResults;
                _tcs.TrySetResult(results?.ToList() ?? new List<ScanResult>());
            }
            else
            {
                _tcs.TrySetResult(new List<ScanResult>());
            }
        }
    }
}
